package com.example.bootredis.canal;

import java.net.InetSocketAddress;
import java.util.List;
 
 
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CanalClientTest {
 
    public static void main(String args[]) {
        // 创建连接，这里的 example 对应
        //端口对应默认是 11111，修改则调整 canal.properties 的 canal.port 参数
        //example 对应 canal.properties 下的 canal.destinations,也是对应这个 example 目录下的 instance.properties 文件配置
        //账号和密码这里，在前面的配置是关掉演示，放空串既可
        CanalConnector connector = CanalConnectors.newSingleConnector(
                new InetSocketAddress("127.0.0.1",11111),
                "example", "", "");
        int batchSize = 1000;
        int emptyCount = 0;
 
        try {
            connector.connect();
            // 防止 deserializer failed报错
            //监听对应的库，article\\..* ，则监听的就是数据库 article 下所有表。也是正则规则，根据业务来，此是在 canal 的配置包含下生效。
            connector.subscribe(".*\\..*");
            connector.rollback();
            int totalEmptyCount = 120;
 
            while (emptyCount < totalEmptyCount) {
                connector.subscribe();
 
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
 
                if (batchId == -1 || size == 0) {
                    emptyCount++;
                    System.out.println("empty count : " + emptyCount);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
 
                } else {
                    emptyCount = 0;
                    printEntry(message.getEntries());
                }
 
                connector.ack(batchId); // 提交确认
                // connector.rollback(batchId); // 处理失败, 回滚数据
            }
 
            System.out.println("empty too many times, exit");
 
        } finally {
 
            connector.disconnect();
        }
 
    }
 
    private static void printEntry(List<Entry> entrys) {
        for (Entry entry : entrys) {
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
                continue;
            }
 
            RowChange rowChage = null;
            try {
                rowChage = RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                        e);
            }
 
            EventType eventType = rowChage.getEventType();
            System.out.println(String.format("===== 打印消费binlog 位置===========binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));
 
            for (RowData rowData : rowChage.getRowDatasList()) {
                //删除取 before
                if (eventType == EventType.DELETE) {
                    printColumn(rowData.getBeforeColumnsList());
                } else if (eventType == EventType.INSERT) {
                    //插入取 after
                    printColumn(rowData.getAfterColumnsList());
                } else {
                    //修改取前后
                    System.out.println("-------before");
                    printColumn(rowData.getBeforeColumnsList());
                    System.out.println("------- after");
                    printColumn(rowData.getAfterColumnsList());
                }
            }
        }
    }
 
    private static void printColumn(List<Column> columns) {
        for (Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
        }
    }
 
}